package www.ld.com.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import www.ld.com.domain.brand.pojo.BrandPO;
import www.ld.com.domain.brand.query.BrandQuery;
import www.ld.com.mapper.BrandMapper;

import javax.annotation.Resource;

@Service
public class BrandService {
    @Resource
    private BrandMapper brandMapper;

    public Page<BrandPO> pageBrandByBrandQuery(BrandQuery brandQuery) {
        return brandMapper.selectPage(
                new Page<BrandPO>(brandQuery.getCurrent(), brandQuery.getSize()),
                new LambdaQueryWrapper<BrandPO>()
                        .select(BrandPO::getId,
                                BrandPO::getName,
                                BrandPO::getStatus,
                                BrandPO::getSort,
                                BrandPO::getLogo,
                                BrandPO::getFirstLetter)
                        .like(StrUtil.isNotBlank(brandQuery.getName()), BrandPO::getName, brandQuery.getName()).orderByAsc(BrandPO::getSort)
        );
    }

    public BrandPO getBrandPOById(String id) {
        return brandMapper.selectById(id);
    }

    @Transactional
    public void saveBrandPO(BrandPO brandPO) {
        brandPO.setFirstLetter(brandNameToPinyin(brandPO.getName()));
        brandMapper.insert(brandPO);
    }

    @Transactional
    public void updateBrandPO(BrandPO brandPO) {
        brandPO.setFirstLetter(brandNameToPinyin(brandPO.getName()));
        brandMapper.updateById(brandPO);
    }

    private char brandNameToPinyin(String name) {
        char firstLetter = PinyinUtil.getFirstLetter(name.charAt(0));
        return Character.toUpperCase(firstLetter);
    }

    @Transactional
    public void deleteBrandPOById(String id) {
        brandMapper.deleteById(id);
    }
}
